import Vue from 'vue'
import Vuex from 'vuex'
import Request from "./Request"
const { platform,PF} = require("../../package.json")
Vue.use(Vuex)
export default new Vuex.Store({
  state: {
    name: sessionStorage.getItem("name") || "",
    uid: sessionStorage.getItem("uid"),
    token: sessionStorage.getItem("token") || 0,
    leader: sessionStorage.getItem("leader") || 0,
    swzg:sessionStorage.getItem("leader") || false,
    message:"",
    bonus_points:"",
    role: "",
    role_id:"",
    swzl: "",
    sw:"",
    resourceList: [],
    authList: "",
    roleList: [],
    pathPermMap: new Map(),
    //平台所有人员列表
    appUserList :[],
    appUserMap:new Map(),
    //平台操作人员列表(主管、商务)
    opUserList:[],
    cascaderOpUserList:[],
    directorList:[],//主管
    businessList:[],//商务
    SdkVersionList:[],
    provinceList:[],
    citysList:[],
    region1List:[],
    region2List:[],
    region3List:[],
  },
  getters: {
    UserInfo: state => {
      return {"name": state.name,"message":state.message,"bonus_points":state.bonus_points,"uid": state.uid, "leader": state.leader,"swzg":state.swzg,"role":state.role,"role_id":state.role_id,"swzl":state.swzl,"sw":state.sw};
    },
    isLogin: state => {
    
      // let b = state.uid > 0 || document.cookie != "";
      // if (b) {
      //   let res = Request.post("exclude","GetUserLoginState",{"uid":state.uid});
      //   if (res.data == null) {
      //       b = true
      //   } else {
      //     b = false
      //   }
      // }
      
      // return b;


      // return state.uid > 0;
      // console.log("document.cookie:",document.cookie);
      return  state.uid > 0 || document.cookie != "";


      // if(state.uid > 0 ) {
      //   return  state.uid > 0 && document.cookie != "";
      // } else {
      //   return  state.uid > 0 || document.cookie == "";
      // }
    },
    Swzg:state=>{
      return state.swzg;
    },
    Role:state=>{
      return state.role
    },
    Swzl:state=>{
      return state.swzl
    },
    Sw:state=>{
      return state.sw;
    },
    ResourceList: state => {
      return state.resourceList;
    },
    AppUserList:state=>{
      return state.appUserList;
    },
    SdkVersionList:state=>{
      return state.SdkVersionList;
    },
    AppUserMap:state=>id=>{
      if(state.appUserMap.has(id)){
        return state.appUserMap.get(id)
      }
      return null
    },
    OpUserList:state => {
      return state.opUserList;
    },
    DirectorList:state=>{
      return state.directorList;
    },
    BusinessList:state=>{
      return state.businessList;
    },
    ProvinceList:state=>{
      return state.provinceList;
    },
    CitysList:state=>{
      return state.citysList;
    },
    Region1List:state => {
      return state.region1List;
    },
    Region2List:state => {
      return state.region2List;
    },
    Region3List:state => {
      return state.region3List;
    },
    PathPermMap:state=>path=>{
      if(state.pathPermMap.has(path)){
        let list = state.pathPermMap.get(path);
        let perms=[];
        list.forEach(perm=>{
          perms.push(perm);
        })
        return perms;
      }else{
        return [];
      }
    },
    PermAuth:state=>(perm)=>{
      let [path,kw] = perm.split(".",2);
      if(state.pathPermMap.has(path)){
        let perms = state.pathPermMap.get(path);
        return perms.indexOf(kw)>-1;
      }else{
        return false;
      }
    },
    CascaderOpUserList:state=>{
      return state.cascaderOpUserList;
    },
  },
  mutations: {
    loadUserInfo(state, data) {
      state.message = data.recharge_points,
      state.bonus_points=data.bonus_points,
      state.name = data.account;
      state.uid = data.id;
      state.leader = data.leader;
      state.swzg = data.swzg;
      state.role = data.role_name;
      state.role_id = data.role_id;
      state.swzl = data.swzl;
      state.sw = data.sw;
      sessionStorage.setItem("name", data.account);
      sessionStorage.setItem("uid", data.id);
      sessionStorage.setItem("leader", data.leader);
    },
    loadUserAccount(state, data) {
      state.uid = 1;
      state.token=data.token
      sessionStorage.setItem("token",data.token);
      sessionStorage.setItem("uid",state.uid);
    },  
    loadUserOut(state, data) {
      state.uid = 0;
      sessionStorage.removeItem("uid");
    },         
    loginOut(state) {
      state.name = "";
      state.message = "";
      state.bonus_points="",
      state.uid = 0;
      state.leader = 0;
      state.swzg = false;
      state.swzl = false;
      state.role = 0;
      state.role_id=0;
      state.sw = 0;
      sessionStorage.clear();
    },
    loadResorceList(state, data) {
      console.log(data,'me');
      state.resourceList = data;
      state.pathPermMap.clear();
      let d = (rinfo)=>{
        if(rinfo.Children&&rinfo.Children.length>0){
          rinfo.Children.forEach(c=>{
            d(c);
          })
        }
        if(rinfo.Perms.length>0){
          let plist = [];
          rinfo.Perms.forEach(perm=>{
            plist.push(perm.Name.split(rinfo.Name+".",2)[1]);
          })
          state.pathPermMap.set(rinfo.Name,plist);
        }
      }
      data.forEach(p=>{
        d(p);
      })
    },
    checkUserAuth(state,perm){
      let [path,kw] = perm.split(".",2);
      if(state.pathPermMap.has(path)){
        let perms = state.pathPermMap.get(path);
        return state.leader>0 && perms.indexOf(kw)>-1;
      }else{
        return false;
      }
    },
    loadAppAllUser(state,data){
      state.appUserList = data;
      state.appUserMap.clear();
      state.appUserList.forEach(item=>{
        state.appUserMap.set(item.Uid,item);
      })
    },
    loadAppOpAllUser(state,data){
      console.log(data)
      state.opUserList = data;
      //分离出主管、商务
      let _directorList = [];
      let _businessList = [];
      state.opUserList.forEach(item=>{
        if(item.Leader == 0){
          if(state.swzl || state.sw){
            //商务专员
            if(item.Uid == state.leader){
              _directorList.push(item);
            }
          }else{
            _directorList.push(item);
          }
        }
        if(state.swzl || state.sw){
          if(item.Uid == state.uid){
            _businessList.push(item)
          }
        }else{
          _businessList.push(item)
        }
      });
      state.directorList = _directorList;
      state.businessList = _businessList;
      //cascaderOpUserList
      let _cascaderList = [];
      let cnt = state.opUserList.length;
      if(state.swzg && state.leader>0){
        let _dList = {"value":state.uid,"label":state.name,children:[]};
        _dList.children.push({"value":state.uid,"label":state.name});
        for(let i = 0;i<cnt;i++){
          let _obj = state.opUserList[i];
          if(_obj.Leader!=state.uid){
            continue
          }
          _dList.children.push({"value":_obj.Uid,"label":_obj.Name});
        }
        _cascaderList.push(_dList);
      } else if(state.swzl){
        let _dList = {"value":0,"label":"",children:[{"value":state.uid,"label":state.name}]};
        for(let i = 0;i<cnt;i++){
          let _obj = state.opUserList[i];
          if(_obj.Uid==state.leader){
            _dList.value = _obj.Uid;
            _dList.label = _obj.Name;
            break;
          }
        }
        _cascaderList.push(_dList);
      }else{
        state.opUserList.forEach(item=>{
          if(item.Leader == 0){
            let _dList = {"value":item.Uid,"label":item.Name,children:[]};
            _dList.children.push({"value":item.Uid,"label":item.Name});
            state.opUserList.forEach(item1=>{
              if(item1.Leader == item.Uid){
                _dList.children.push({"value":item1.Uid,"label":item1.Name});
              }
            })
            _cascaderList.push(_dList);
          }
        })
      }
      state.cascaderOpUserList = _cascaderList;
      // console.log(state.cascaderOpUserList)
    },
    loadSdkVersionList(state,data){
      state.SdkVersionList = data
    },
    loadProvinceList(state,data) {
      if (platform.includes("cn"))  {
        let proObj = {};
        if (data.ProvinceList != null && data.CityList != null) {
          data.ProvinceList.forEach(pro => {
            proObj[pro.Id] = {"id": pro.Id, "name": pro.Name, "list": []};
            state.provinceList.push({"id": pro.Id, "name": pro.Name})
          })
          data.CityList.forEach(city => {
            proObj[city.ParentId].list.push({"id": city.Id, "name": city.Name})
          })
          for (var key in proObj) {
            state.citysList.push(proObj[key]);
          }
        }
      }else{
        //
        state.region1List =[];
        state.region2List = [];
        state.region3List = [];
        let proObj1={};
        let proObj2={};
        if(data.Region1 != null && data.Region2 != null && data.Region3 != null){
          data.Region1.forEach(pro=>{
            proObj1[pro.id] = {"id":pro.id,"name":pro.name,"list":[]};
            state.region1List.push({"id":pro.id,"name":pro.name})
          });
          data.Region2.forEach(area=>{
            proObj1[area.parentId].list.push({"id":area.id,"name":area.name})
            proObj2[area.id]= {"id":area.id,"name":proObj1[area.parentId].name+"-"+area.name,"list":[]};

          });
          for(var key in proObj1){
            state.region2List.push(proObj1[key]);
          }
          data.Region3.forEach(city=>{
            proObj2[city.parentId]["list"].push({"id":city.id,"name":city.name});
          })
          for(var key in proObj2){
            state.region3List.push(proObj2[key]);
          }
        }
      }
    }
  },
  actions: {
    async RequestLogin({ commit }, accountData) {
      let res = await Request.post("login", "", accountData);
      if (res.code == 0) {
        commit("loadUserAccount",{token:res.data.cookie})
      }
    },    
    async RequestSysDefine({commit}){
      let res = await Request.post("exclude", "GetSysDefine");
      if (res.code == 0) {
        if(res.data.UserInfo!=null){
          // console.log(res.data.UserInfo)
          commit("loadUserInfo",res.data.UserInfo)
        }
        if(res.data.ResourceList!=null){
          commit("loadResorceList", res.data.ResourceList)
        }
        if(res.data.AllUserList !=null){
          commit("loadAppAllUser", res.data.AllUserList)
        }
        if(res.data.BusinessList !=null){
          commit("loadAppOpAllUser", res.data.BusinessList)
        }
        if(res.data.SdkVersionList !=null){
          commit("loadSdkVersionList", res.data.SdkVersionList)
        }
        if (platform.includes("cn")) {
          commit("loadProvinceList", {"ProvinceList": res.data.ProvinceList, "CityList": res.data.CityList})
        }else{
          commit("loadProvinceList", {"Region1": res.data.Region1, "Region2": res.data.Region2,"Region3":res.data.Region3})
        }
      }
    },
    async RequestLoginOut({ commit }) {
      let res = await Request.post("loginOut", "");
      if (res.code == 0) {
        commit("loginOut")
      }
    },  
    // async RequestUserInfo({commit}){
    //   let res = await Request.post("exclude","GetUserInfo");
    //   console.log("res == ",res)
    //   if(res.code==0){
    //     console.log("xxx == ",res.data)
    //     commit("loadUserInfo", res.data)
    //   }
    // }
  }
})
